package com.zeronx.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.servlet.i18n.CookieLocaleResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Locale;

/**
 * @author foreee on 2017/3/31.
 * @version 1.0
 */
//@Component
public class MyStringMessageConvert extends StringHttpMessageConverter {

    @Autowired
    private HttpServletRequest request;
    @Autowired
    private MessageSource messageSource;
    private String charset;
    public static final String LOCALE_REQUEST_ATTRIBUTE_NAME = CookieLocaleResolver.class.getName() + ".LOCALE";
    public MyStringMessageConvert() {
        super();
    }
    public MyStringMessageConvert(String charset) {
        super(Charset.forName(charset));
        this.charset = charset;
    }
    @Override
    protected void writeInternal(String str, HttpOutputMessage outputMessage) throws IOException {
        Locale locale2 = (Locale) request.getAttribute(LOCALE_REQUEST_ATTRIBUTE_NAME);
        GenericTokenParserUtil rj = new GenericTokenParserUtil("#{", "}", locale2, messageSource);
        str = rj.parse(str);
        long length;
        // 因为可能将返回的字符串转为i18n 的中文或英文，会造成与原始的字符长度不一样，在这里重新设置新的长度。
        try {
            length = (long) str.getBytes(Charset.forName(charset)).length;
        }
        catch (Exception ex) {
            throw new IllegalStateException(ex);
        }
        outputMessage.getHeaders().setContentLength(length);
        super.writeInternal(str,outputMessage);
    }
}
